package com.by.component.vod;

import cn.hutool.core.util.RandomUtil;
import com.by.component.tencent.TencentAccessProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import static com.by.toolkit.utils.ExceptionUtil.getStackTrace;

@Slf4j
@Component
public class VodSupport {

    @Resource
    private TencentAccessProperties tencentAccessProperties;

    private static final String HMAC_ALGORITHM = "HmacSHA1"; //签名算法

    private static byte[] byteMerger(byte[] byte1, byte[] byte2) {
        byte[] byte3 = new byte[byte1.length + byte2.length];
        System.arraycopy(byte1, 0, byte3, 0, byte1.length);
        System.arraycopy(byte2, 0, byte3, byte1.length, byte2.length);
        return byte3;
    }

    private static String base64Encode(byte[] buffer) {
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(buffer);
    }

    // 获取签名
    public String getUploadSignature(Long vodSubAppId, String vodFileCode, String procedure) {
        String contextStr = "";
        // 生成原始参数字符串
        long currentTime = System.currentTimeMillis() / 1000;
        // 10分钟有效期
        long endTime = currentTime + 600;
        contextStr += "secretId=" + URLEncoder.encode(tencentAccessProperties.getSecretId(), StandardCharsets.UTF_8);
        contextStr += "&currentTimeStamp=" + currentTime;
        contextStr += "&expireTime=" + endTime;
        contextStr += "&random=" + RandomUtil.randomInt(Integer.MAX_VALUE);
        contextStr += "&vodSubAppId=" + vodSubAppId;
        contextStr += "&storageRegion=ap-beijing";
        contextStr += "&taskNotifyMode=Finish";
        contextStr += "&sourceContext=" + vodFileCode;
        if (StringUtils.isNotBlank(procedure)) {
            contextStr += "&procedure=" + procedure;
        }
        try {
            Mac mac = Mac.getInstance(HMAC_ALGORITHM);
            SecretKeySpec secretKey = new SecretKeySpec(tencentAccessProperties.getSecretKey().getBytes(StandardCharsets.UTF_8), mac.getAlgorithm());
            mac.init(secretKey);
            byte[] hash = mac.doFinal(contextStr.getBytes(StandardCharsets.UTF_8));
            byte[] sigBuf = byteMerger(hash, contextStr.getBytes(StandardCharsets.UTF_8));
            return base64Encode(sigBuf)
                    .replace(" ", "")
                    .replace("\n", "")
                    .replace("\r", "");
        } catch (Exception e) {
            log.error("[VodSupport][getUploadSignature] hasException:[{}] ", getStackTrace(e));
            return null;
        }
    }

}
